/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.convert.vienna.lang;

import at.schauer.gregor.vienna.convert.vienna.SimpleConverter;
import at.schauer.gregor.vienna.exception.ViennaException;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Gregor Schauer
 */
public class MethodConverter implements SimpleConverter<Method> {
	private static final Pattern SEPARATOR_PATTERN = Pattern.compile(",");

	@Override
	public Method sourceToTarget(String source, Class<? extends Method> targetClass) {
		int pos = source.indexOf('(');
		String fqmn = source.substring(0, pos);
		String fqcn = fqmn.substring(0, fqmn.lastIndexOf('.'));
		String mn = fqmn.substring(fqmn.lastIndexOf('.') + 1);

		String paramString = source.substring(pos + 1, source.lastIndexOf(')'));
		String[] paramTypes = StringUtils.hasLength(paramString) ? SEPARATOR_PATTERN.split(paramString) : new String[0];
		List<Class<?>> classes = org.apache.commons.lang3.ClassUtils.convertClassNamesToClasses(Arrays.asList(paramTypes));
		Class<?>[] classesArray = ClassUtils.toClassArray(classes);
		try {
			return ReflectionUtils.findMethod(org.apache.commons.lang3.ClassUtils.getClass(fqcn), mn, classesArray);
		} catch (ClassNotFoundException e) {
			throw new ViennaException(e);
		}
	}

	@Override
	public String targetToSource(Method target) {
		StringBuilder sb = new StringBuilder();
		sb.append(ClassUtils.getQualifiedMethodName(target)).append('(');
		Class[] params = target.getParameterTypes();
		for (int j = 0; j < params.length; j++) {
			sb.append(params[j].getName());
			if (j < params.length - 1) {
				sb.append(',');
			}
		}
		sb.append(')');
		return sb.toString();
	}
}
